package cqrtplm.aop;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.hustcad.plm.pdm.workflow.config.ContainerInstanceFactory;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainerView;
import com.ty.basic.constant.TableTypeConstrant;
import cqrtplm.mapper.RTProjectCodeMapper;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.List;

/**
 * 非0版本物料、工艺路线不允许发起普通流程
 */
@Aspect
@Component
public class StartProcessAop {
    @Resource
    private RTProjectCodeMapper projectCodeMapper;
    @SneakyThrows
//    @Before("execution(* com.hustcad.plm.pdm.flowbusiness.service.TyplmContainerViewCommonService.createAndStartContainerView(..))")
    public void startProcess(JoinPoint point) {
        HttpServletRequest request = (HttpServletRequest) point.getArgs()[1];
        String baseObjectOtype = request.getParameter("baseObjectOtype");
        WorkFlowContainerView workFlowContainerView;
        if (StringUtils.isBlank(baseObjectOtype)) {
            workFlowContainerView = JSON.parseObject(request.getParameter("param"),
                                                     WorkFlowContainerView.class);
            request.setAttribute("isParent", true);
        } else {
            Class<? extends WorkFlowContainerView> containerViewClass = ContainerInstanceFactory.getTargetContainerViewClass(
                    baseObjectOtype);
            if (containerViewClass == null) {
                containerViewClass = WorkFlowContainerView.class;
            }

            workFlowContainerView = JSON.parseObject(request.getParameter("param"),
                                                     containerViewClass);
            request.setAttribute("isParent", false);
        }

        if (null != workFlowContainerView && !StringUtils.isBlank(workFlowContainerView.getCode())) {
            baseObjectOtype = workFlowContainerView.getBaseObjectOtype();
            if (TableTypeConstrant.TY_PJ_CHANGEINFO_OTYPE.equals(baseObjectOtype)) {
                BigInteger baseObjectOid = workFlowContainerView.getBaseObjectOid();
                List<String> projectNameList = projectCodeMapper.selectProjectNameByChgId(baseObjectOid.toString());
                if (CollUtil.isNotEmpty(projectNameList)) {
                    workFlowContainerView.setName("\"" + projectNameList.get(0) + "\" 项目变更审批流程");
                }
            }
            request.setAttribute("workFlowContainerView", workFlowContainerView);
        }
    }
}
